package com.network.client;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.network.pojo.Result;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.*;
import java.util.Scanner;


// @Component
@Service
public class ClientService {

    // @PostConstruct
    public void startClient(String username) throws IOException {

//        // json格式转化为字符串
//        ObjectMapper objectMapper = new ObjectMapper();
//        JsonNode jsonNode=objectMapper.readTree(String.valueOf(result));
//        //获取数据
//        int id=jsonNode.path("data").path("id").asInt();
//        String username=jsonNode.path("data").path("username").asText();


        System.out.println("--------客户端启动----------");
        //获取本地的ip地址
        InetAddress ip = null;
        try {
            ip = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        //创建socket与服务端请求连接
        Socket socket = new Socket(ip.getHostAddress(), 8888);

        new ClientReaderThread(socket).start();

        //获取一个字节输出流发数据给服务端
        OutputStream os = socket.getOutputStream();

        //将字节流包装成数据流
        DataOutputStream dos = new DataOutputStream(os);

        //开始写出数据
        Scanner sc = new Scanner(System.in);
        while (true) {
            // 在这里进行写入消息,换为vue
            String msg = sc.nextLine();
            // String msg = acceptHttp();
            if ("exit".equals(msg)) {
                dos.close();
                socket.close();
                break;
            }

            dos.writeUTF(username+": "+msg);
            dos.flush();
        }


    }

//    public String acceptHttp()
//    {
//        try {
//            // 创建 URL 对象
//            URL url = new URL("http://localhost:8082/send");
//
//            // 打开连接
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//
//            // 设置请求方法为 POST
//            connection.setRequestMethod("POST");
//
//            // 获取输入流
//            InputStream inputStream = connection.getInputStream();
//
//            // 创建 BufferedReader 读取输入流
//            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//
//            // 读取响应内容
//            String line;
//            StringBuilder response = new StringBuilder();
//            while ((line = reader.readLine()) != null) {
//                response.append(line);
//            }
//
//            // 关闭资源
//            reader.close();
//            inputStream.close();
//            connection.disconnect();
//
//            // 打印响应内容
//            return response.toString();
//        } catch (IOException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }


}
